﻿// Copyright: 2012 
// Author: Minh Vu - YoungJ
// File name: ReadnWrite.cs
// Solution: getlink
// Project: MediaFire
// Time: 3:12 PM 02/05/2012

using System.Collections.Generic;
using System.IO;

namespace MediaFire
{
    public class ReadnWrite
    {
        private const string _filename = "files.txt";
        public static void Write(List<FileDownload> files, string filename = null)
        {
            if (filename == null)
                filename = _filename;

            if (File.Exists(filename))
                File.Delete(filename);
            using (var stream = new StreamWriter(new FileStream(filename, FileMode.Create)))
            {
                foreach (var file in files)
                {
                    stream.WriteLine(string.Format("{0} ; {1} ; {2}", file.Filename, file.QuickKey, file.Size));
                }
            }
        }

        public static List<FileDownload> Read(string filename = null)
        {
            if (filename == null)
                filename = _filename;
            if (!File.Exists(filename)) return null;
            using (var stream = new StreamReader(filename))
            {
                string line;
                var files = new List<FileDownload>();
                while ((line = stream.ReadLine()) != null)
                {
                    var arr = line.Split(';');
                    if (arr.Length < 3) return null;
                    var file = new FileDownload { Filename = arr[0].Trim(), QuickKey = arr[1].Trim(), Size = arr[2].Trim() };
                    files.Add(file);
                }
                return files;
            }
        }
    }
}